import { ActionContext } from 'vuex'
import { cloneDeep } from 'lodash'
import { fetchLogin, getInfo } from '@/api/system/user'
import { removeToken, setToken } from '@/utils/auth'
import { IUserState, IUserInfo } from '@/interface/user'
import { IStore } from '@/store/types'

export const actions = {
  /**
   * @description 登录
   */
  async login({ commit }: ActionContext<IUserState, IStore>, userInfo: IUserInfo) {
    try {
      const response = await fetchLogin(userInfo)
      const { token, refreshToken } = response
      commit('setToken', token)
      commit('setRefreshToken', refreshToken)
      setToken(token)
      sessionStorage.setItem('refreshToken', refreshToken)

      return Promise.resolve(response)
    } catch (e) {
      return Promise.reject(e)
    }
  },

  /**
   * @description 退出登录
   */
  async logout({ commit }: ActionContext<IUserState, IStore>) {
    commit('setToken', '')
    removeToken()
    commit('SET_MENUS', [])
    commit('SET_INFO', '')
    return Promise.resolve(true)
  },

  /** */
  async getInfo({ commit }: ActionContext<IUserState, IStore>) {
    try {
      const res = await getInfo()
      const { menu, activeUsers } = cloneDeep(res)
      commit('SET_INFO', activeUsers)
      commit('SET_MENUS', menu)

      return Promise.resolve(menu)
    } catch (error) {
      return Promise.reject(error)
    }
  },
}
